#!/usr/bin/env bash
JAVA_HOME=/usr/local/java8/jdk1.8.0_141
#服务名称
SERVICE_NAME=$1
#jar名称
JAR_NAME=$SERVICE_NAME*\.jar
#工作路径
WORK_DIR=/home/microservice
#服务存放父目录
SERVICE_DIR=$WORK_DIR/$SERVICE_NAME
#进程id
PID=pid/$SERVICE_NAME\.pid
#环境
ENV=$2
PEER1="172.27.60.71"
PEER2="172.27.60.70"

#初始化，检查文件夹是否存在
init(){
    cd $WORK_DIR
    if [ ! -d "$SERVICE_NAME" ]; then
        mkdir $SERVICE_NAME
    fi
    cd $SERVICE_DIR
    if [ ! -d "logs" ]; then
        mkdir logs
    fi
    if [ ! -d "pid" ]; then
        mkdir pid
    fi
    if [ ! -d "records" ]; then 
        mkdir records
    fi
    #进入jar目录执行jar
    cd $SERVICE_DIR/jar
}

#function start
start(){
    init
    if [ "$SERVICE_NAME" == "eureka-server" ]; then
        peer=`hostname -i`
        echo "hostname is $peer"
        if [ "$peer" == $PEER1 ]
        then
            host_name="peer1"
        elif [ "$peer" == $PEER2 ]
        then
            host_name="peer2"
        else
            echo "此主机不是宿主主机"
            exit 0
        fi
        nohup $JAVA_HOME/bin/java -jar -Dspring.profiles.active=$ENV -Deureka.hostname=$host_name $JAR_NAME >$SERVICE_DIR/logs/catalina.out 2>&1 &

    elif [ "$SERVICE_NAME" == "minifranchise" ]; then
        nohup $JAVA_HOME/bin/java -jar $JAR_NAME >$SERVICE_DIR/logs/catalina.out 2>&1 &
    else
        nohup $JAVA_HOME/bin/java -jar -Dspring.profiles.active=$ENV $JAR_NAME >$SERVICE_DIR/logs/catalina.out 2>&1 &
    fi
    if [ ! -d "$SERVICE_DIR/$PID" ]; then
        touch $SERVICE_DIR/$PID
    fi
    echo "执行成功 [$!]"
    echo $! > $SERVICE_DIR/$PID
    echo "#### start $SERVICE_NAME"
}

#function stop
stop(){
    cd $SERVICE_DIR
    if [ -f "$SERVICE_DIR/$PID" ]; then
        kill `cat $SERVICE_DIR/$PID`
        rm -rf $SERVICE_DIR/$PID
    fi
    echo "#### stop $SERVICE_NAME"
    sleep 3
    TEMP_PID=`ps -ef | grep -w "$SERVICE_NAME" | grep "java" | awk '{print $2}'`
    if [ "$TEMP_PID" == "" ]; then
        echo "#### $SERVICE_NAME process not exists or stop success"
    else
        echo "#### $SERVICE_NAME process pid is:$TEMP_PID ."
        kill -9 $TEMP_PID
    fi
}

case "$3" in

    start)
    stop
    sleep 2
    start
        ;;

    stop)
    stop
        ;;

    restart)
        stop
        sleep 2
        start
        echo "#### restart $SERVICE_NAME"
        ;;

    *)
       ## restart
       stop
       sleep 2
       start
       ;;

esac
exit 0


